<?php

class VS_Auth_Adapter implements Zend_Auth_Adapter_Interface {
	
	const WRONG_PW_MSG = 'Password is invalid';
	const NOT_FOUND_MSG = 'Account not found';
	
	/*
	 * @var Model_User
	 */
	protected $_user = NULL;
	/**
	 * @var string
	 */
	protected $_password = '';
	
	/**
	 * 
	 * @var string
	 */
	protected $_username = '';

	/**
	 * Default Constructor
	 * 
	 * @param string $username
	 * @param string $password
	 */
	public function __construct($username, $password)
	{
		$this->_username = $username;
		$this->_password = $password;	
	}
	
	/**
	 * Authentication Calback function
	 * 
	 * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed.
	 * @return Zend_Auth_Result
	 */
	public function authenticate()
	{
		try {
			$this->_user = Model_User::authenticate($this->_username, $this->_password);
			return $this->_createResult(Zend_Auth_Result::SUCCESS);
		} catch(Exception $e) {
			if($e->getMessage() === Model_User::WRONG_PW) {
				return $this->_createResult(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array(self::WRONG_PW_MSG));
			} else if($e->getMessage() === Model_User::NOT_FOUND) {
				return $this->_createResult(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, array(self::NOT_FOUND_MSG));
			} else {
				echo '<pre>';
				die($e->getMessage() . "\n" . $e->getTraceAsString());
			}
		}
	}
	
	/**
	 * 
	 */
	public function getUserId()
	{
		return $this->_user->id;
	}
	
	/**
	 * 
	 * @param int $code
	 * @param array $messages
	 */
	private function _createResult($code, $messages = array())
	{
		return new Zend_Auth_Result($code, $this->_user, $messages);
	}
	
};
